﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using Aandelendelen.Mail;
using Aandelendelen.Db;

namespace Aandelendelen.Admin
{
	public partial class AdminSendMail : AdminBaseForm
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			if (!this.IsPostBack)
			{
				this.btnPreview.OnClientClick = "ShowPreview('" + this.tbContent.ClientID + "', '" + "lblTest" + "'); return;";
				this.btnRTECopy.OnClientClick = "GetRTE('" + this.tbContent.ClientID + "', '" + "lblTest" + "'); return;";
				this.PopulateSubjects();
			}
			else
			{
				if (Request["__EVENTTARGET"] == this.ddlSubject.ClientID)
				{
					this.PopulateContent();
				}
				else
				{
					this.btnSend.Enabled = false;
					this.Send();
				}
			}
		}

		private void Send()
		{
			//AdminMail adminMail = new AdminMail(this.ddlSubject.SelectedValue, this.tbContent.Text);
			AdminMail adminMail = new AdminMail(this.tbCustomSubject.Text, this.tbContent.Text);

			Query query = new Query("s_getallemail");
			ResultSet resultSet = (ResultSet)query.Execute();

			BulkEMail emails = new BulkEMail();

			for (int i = 0; i < resultSet.Count; i++)
			{
				EMail newMail = new EMail(adminMail);
				newMail.Recipients = (string)resultSet[i, 0];

				emails.Add(newMail);
			}

			emails.Send(false);
		}

		private void PopulateSubjects()
		{
			XmlDocument doc = new XmlDocument();

			string path = HttpContext.Current.Server.MapPath("/App_Data/AdminMail.xml");

			doc.Load(path);

			XmlNodeList nodes = doc.SelectNodes("/aandelendelen/mail");

			foreach (XmlNode node in nodes)
			{
				string name = node.Attributes["name"].Value;
				string subject = node.Attributes["subject"].Value;

				ListItem item = new ListItem(name + " - " + subject, name);
				this.ddlSubject.Items.Add(item);
			}

			this.PopulateContent();
		}

		private void PopulateContent()
		{
			string name = this.ddlSubject.SelectedValue;

			AdminMail mail = new AdminMail(name);

			this.tbCustomSubject.Text = mail.Subject;
			this.tbContent.Text = mail.SendBody;
		}
	}
}